<?php
/* 
 *  The MIT License
 * 
 *  Copyright 2011 http://
 * 
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 * 
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 * 
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */

/**
 * Classe per il controllo della cache del browser
 *
 * @author Fabrizio Filieri
 */
class Cache
{
	public static function checkFileModified($filename)
	{
		$modified = filemtime($filename);
		$request = getallheaders();

		header('Expires: ');
		header('Cache-Control: ');
		header('Pragma: ');
		
		if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
			$etag = $_SERVER['HTTP_IF_NONE_MATCH'];
		else
			$etag = self::getEtag($filename);


		if (isset($request['If-Modified-Since']))
		{
			$request_modified = explode(';', $request['If-Modified-Since']);
			$request_modified = strtotime($request_modified[0]);

			if ($modified <= $request_modified) // il file non è stato modificato
			{
				// intestationi di file non modificato
				header('HTTP/1.1 304 Not Modified');
				header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $modified) . ' GMT');
				header("Etag: ".$etag);

				exit();
			}
			else // il file è stato modificato
				$etag = self::getEtag($filename);
		}

		header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $modified) . ' GMT');
		header("Etag: ".$etag);
	}

	public static function getEtag($filename)
	{
		return '"'.filesize($filename)."-".filemtime($filename)."-".rand(1000, 9999).'"';
	}
}
?>
